﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Demo.Framework
{
    class Polygon
    {
        List<VertexPositionTexture> vertexList = new List<VertexPositionTexture>();
        private VertexBuffer vertexBuffer;
        private GraphicsDevice _graphics;
        VertexPositionTexture[] verts;
        private BasicEffect _basicEffect;

        public Polygon(GraphicsDevice graphics)
        {
            _graphics = graphics;
            int size = 100;
            int terrainWidth = 300;
            int terrainHeight = 300;
            int x = 300;
            int z = 300;
            int texScale = 5;

            //for (int x = 0; x < terrainHeight*5; x += size)
            //{
            //    for (int z = 0; z < terrainWidth*5; z += size)
            //    {

                    vertexList.Add(new VertexPositionTexture(new Vector3(x, 0f, -z), new Vector2(0, 0)));
                    vertexList.Add(new VertexPositionTexture(new Vector3(x, 0f, -(z + size)), new Vector2(texScale, 0)));
                    vertexList.Add(new VertexPositionTexture(new Vector3(x + size, 0, -z), new Vector2(0, texScale)));
                    vertexList.Add(new VertexPositionTexture(new Vector3(x + size, 0, -(z + size)), new Vector2(texScale, texScale)));
            //    }
            //}

            // Set cullmode to none
            RasterizerState rs = new RasterizerState();
            rs.CullMode = CullMode.CullCounterClockwiseFace;
            _graphics.RasterizerState = rs;

            _basicEffect = new BasicEffect(_graphics);
            vertexBuffer = new VertexBuffer(_graphics, typeof(VertexPositionTexture), vertexList.Count, BufferUsage.WriteOnly);
            vertexBuffer.SetData<VertexPositionTexture>(vertexList.ToArray()); 
        }

        public void Draw(Texture2D texture)
        {
            _basicEffect.Texture = texture;
            _basicEffect.TextureEnabled = true;
            _basicEffect.World = Matrix.Identity;
            _basicEffect.View = GameEngine.Instance.Camera.View;
            _basicEffect.Projection = GameEngine.Instance.Camera.Projection;

            foreach (EffectPass pass in _basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                _graphics.DrawUserPrimitives<VertexPositionTexture>(PrimitiveType.TriangleStrip, vertexList.ToArray(), 0, 2);
                //_graphics.SetVertexBuffer(vertexBuffer);
                //_graphics.DrawPrimitives(PrimitiveType.TriangleStrip, 0, vertexBuffer.VertexCount);
            }
            

        }
    }
}
